package com.wuxianedu.recyclerview.gridrecycler;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.wuxianedu.recyclerview.R;
import com.wuxianedu.recyclerview.adddivider.DividerItemDecoration;

public class MainActivity extends AppCompatActivity {

    private String[] date;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.id_recyclerview);
       // recyclerView.setLayoutManager(new LinearLayoutManager(this));
      //  recyclerView.setLayoutManager(new GridLayoutManager(this,4));
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL));
        //添加分割线需要调用该方法
        recyclerView.addItemDecoration(new DividerGridItemDecoration(this));
        recyclerView.setAdapter(new MyAdapter());
    }

    private void initData() {
        date = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
                "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z","a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
                "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
    }

    class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        /**
         * 实现item布局，并包装到viewholder中
         *
         * @param parent
         * @param viewType
         * @return
         */
        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.item_recycler, parent, false);
            MyViewHolder holder = new MyViewHolder(view);
            return holder;
        }

        /**
         * 为viewhodler中的视图绑定数据
         *
         * @param holder
         * @param position
         */
        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            holder.tv.setText(date[position]);

            ViewGroup.LayoutParams lp = holder.tv.getLayoutParams();
            lp.height = (int) (100 + Math.random() * 300);

            holder.tv.setLayoutParams(lp);

        }

        @Override
        public int getItemCount() {
            return date.length;
        }
    }
}
